{
 "metadata": {},
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "Matplotlib: hint on diagrams\n",
      "======================================================================\n",
      "\n",
      "Hinton diagrams with matplotlib\n",
      "-------------------------------\n",
      "\n",
      "Hinton diagrams are a way of visualizing numerical values in a\n",
      "matrix/vector, popular in the neural networks and machine learning\n",
      "literature. The area occupied by a square is proportional to a value's\n",
      "magnitude, and the colour (black or white in this case) indicates its\n",
      "sign (positive/negative).\n",
      "\n",
      "![](files/attachments/Matplotlib_HintonDiagrams/hinton.png)\n",
      ")# "
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "import numpy as N\n",
      "import pylab as P\n",
      "\n",
      "def _blob(x,y,area,colour):\n",
      "    \"\"\"\n",
      "    Draws a square-shaped blob with the given area (< 1) at\n",
      "    the given coordinates.\n",
      "    \"\"\"\n",
      "    hs = N.sqrt(area) / 2\n",
      "    xcorners = N.array([x - hs, x + hs, x + hs, x - hs])\n",
      "    ycorners = N.array([y - hs, y - hs, y + hs, y + hs])\n",
      "    P.fill(xcorners, ycorners, colour, edgecolor=colour)\n",
      "\n",
      "def hinton(W, maxWeight=None):\n",
      "    \"\"\"\n",
      "    Draws a Hinton diagram for visualizing a weight matrix. \n",
      "    Temporarily disables matplotlib interactive mode if it is on, \n",
      "    otherwise this takes forever.\n",
      "    \"\"\"\n",
      "    reenable = False\n",
      "    if P.isinteractive():\n",
      "        P.ioff()\n",
      "    P.clf()\n",
      "    height, width = W.shape\n",
      "    if not maxWeight:\n",
      "        maxWeight = 2**N.ceil(N.log(N.max(N.abs(W)))/N.log(2))\n",
      "        \n",
      "    P.fill(N.array([0,width,width,0]),N.array([0,0,height,height]),'gray')\n",
      "    P.axis('off')\n",
      "    P.axis('equal')\n",
      "    for x in xrange(width):\n",
      "        for y in xrange(height):\n",
      "            _x = x+1\n",
      "            _y = y+1\n",
      "            w = W[y,x]\n",
      "            if w > 0:\n",
      "                _blob(_x - 0.5, height - _y + 0.5, min(1,w/maxWeight),'white')\n",
      "            elif w < 0:\n",
      "                _blob(_x - 0.5, height - _y + 0.5, min(1,-w/maxWeight),'black')\n",
      "    if reenable:\n",
      "        P.ion()\n",
      "    P.show()"
     ],
     "language": "python",
     "metadata": {},
     "outputs": []
    }
   ],
   "metadata": {}
  }
 ]
}